package com.example.PolimiAssistant;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import com.Wsdl2Code.WebServices.PolimiAssistant.CourseExamInfo;
import com.Wsdl2Code.WebServices.PolimiAssistant.UserProfile;
import com.example.PolimiAssistant.adapters.ProfileCourseListAdapter;
import com.example.PolimiAssistant.common.CommonActivity;
import com.example.PolimiAssistant.utils.PreferencesManager;
import com.example.PolimiAssistant.utils.UserDataManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Profile.java
 *
 * This activity display the basic information of the user and the
 * academic profile: courses completed, mark and average.
 */
public class Profile extends CommonActivity {

    /**
     * The list of courses for each course type [ie. passed/not passed]
     */
    private Map<String, List<CourseExamInfo>> courses;

    /**
     * The list of course types [ie. passed/not passed]
     */
    private ArrayList<String> courseGroups;

    /**
     * Adapter for the course list with the exapandable list view
     */
    private ProfileCourseListAdapter profileCourseAdapter;

    /**
     * Expandable list view object
     */
    private ExpandableListView expandableListView;

    public void onCreate(Bundle savedInstanceState) {

        //Activity initialization
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_screen);

        //Update the information on the views
        new UpdateData().execute();
    }

    public void updateViews(UserProfile poliUser) {

        Log.i(TAG, "Updating the basic user information...");

        //1. Update the views from the basic information

        TextView name = (TextView) findViewById(R.id.profile_name_value);
        name.setText(poliUser.name+" "+poliUser.surname);

        TextView enrollmentCode = (TextView) findViewById(R.id.profile_enrollment_code_value);
        enrollmentCode.setText(poliUser.matricola);

        TextView email = (TextView) findViewById(R.id.profile_email_value);
        email.setText(poliUser.email);

        TextView degree = (TextView) findViewById(R.id.profile_degree_value);
        degree.setText(poliUser.user_major_name);

        TextView school = (TextView) findViewById(R.id.profile_school_value);
        school.setText(poliUser.user_school_name);

        Log.i(TAG, "Updating the user course list  information...");

        //2. Update the views from the academic information

        //2.1 Update the score
        TextView score = (TextView) findViewById(R.id.profile_score_value);
        score.setText(Double.toString(poliUser.average_grade));

        TextView credits = (TextView) findViewById(R.id.profile_total_credits_value);
        credits.setText(Double.toString(poliUser.total_credits));

        //2.2 Update the courses expandable lists

        //Declare which layout will be used for the list and which courses list
        expandableListView = (ExpandableListView)findViewById(R.id.profile_courses_list);
        profileCourseAdapter = new ProfileCourseListAdapter(courseGroups, courses);

        profileCourseAdapter.setInflater(LayoutInflater.from(context));
        expandableListView.setAdapter(profileCourseAdapter);

    }

    private class UpdateData extends AsyncTask<Void, Void, UserProfile>
    {

        //1. Create the loading dialog
        ProgressDialog loadingDialog;
        {
            loadingDialog = new ProgressDialog(Profile.this);
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            //2. Set the message and show the dialog
            loadingDialog.setMessage("Loading...");
            loadingDialog.show();
        }

        @Override
        protected UserProfile doInBackground(Void... params) {

            //3. Get the token from the preferences
            PreferencesManager preferencesManager;
            preferencesManager = new PreferencesManager(context);
            String token = preferencesManager.getToken();

            Log.i(TAG, "Retrieved token from the preferences: "+token);

            //4. Obtain the user profile from the data manager and manage possible errors
            UserProfile poliUser;
            poliUser = UserDataManager.getUserProfile(token);

            if(poliUser != null){

                //5. Obtain the courses from the data manager and populate course groups
                courses = UserDataManager.getActiveAndCompletedCourses(poliUser);

                courseGroups = new ArrayList<String>();
                courseGroups.addAll(courses.keySet());

                Log.i(TAG, "Retrieved user: "+poliUser.name+" basic info and courses list");

            }

            return poliUser;
        }

        @Override
        protected void onPostExecute(UserProfile poliUser) {

            super.onPostExecute(poliUser);

            //6. Check if the token is valid and log out the user acordingly and manage WS errors
            if(poliUser == null){

                Toast.makeText(context,
                        "The web service is not available in this moment, try again later",
                        Toast.LENGTH_LONG)
                        .show();


            }else if(!poliUser.valid){

                Log.i(TAG, "The token is not valid anymore");
                invalidTokenLogOut();

            }else{

                //7. Update the corresponding views
                updateViews(poliUser);
            }

            //Dismiss the loading dialog
            loadingDialog.dismiss();
        }

    }
}